package com.example.mallauthserver.controller;

import com.alibaba.fastjson.JSON;
import com.example.mallauthserver.VO.LoginVo;
import com.example.mallauthserver.VO.UserRegisterVo;
import com.example.mallauthserver.fefin.MembeFeginService;
import com.example.mallauthserver.fefin.ThirdPartFeginService;
import com.msb.common.constant.AuthConstant;
import com.msb.common.constant.SmsConstant;
import com.msb.common.exception.BizCodeEnume;
import com.msb.common.utils.R;
import com.msb.common.vo.MemberVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: xixifeng
 * @Date: 2022/11/4 - 11 - 04 - 19:19
 * @Description: com.example.mallauthserver.controller
 * @version: 1.0
 */
@Controller
public class loginController {

    @Autowired
    ThirdPartFeginService thirdPartFeginService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    MembeFeginService membeFeginService;


    /**
     * 短信发送
     * @param phone
     * @return
     */
    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendSmsCode(@RequestParam("phone") String phone){

        Object redisCode = redisTemplate.opsForValue().get(SmsConstant.SMS_CODE_PERFIX + phone);
        if (redisCode != null) {
            String s = redisCode.toString();
            if ("".equals(s)) {
                //获取验证码后面的时间
                Long l = Long.parseLong(redisCode.toString().split("_")[1]);
                //小于60秒说明在重复进行发送了，这种情况是不允许的，所以给了下面一个报错信息
                if (System.currentTimeMillis() - l <= 6000) {
                    return R.error(BizCodeEnume.VALID_SMS_EXCEPTION.getCode(), BizCodeEnume.VALID_SMS_EXCEPTION.getMsg());
                }
            }
        }
        //随机生成验证码
        String code = UUID.randomUUID().toString().substring(0, 5);
        thirdPartFeginService.sendSmsCode(phone, code);

        //把生成的验证码和当前时间储存到redis，用_做为分隔符
        code=code+"_"+System.currentTimeMillis();
        System.out.println("---------------------->"+code);
        //将生成的验证码保存到redis  sms:code:13657061264,12345
        redisTemplate.opsForValue().set(SmsConstant.SMS_CODE_PERFIX+phone,code,10, TimeUnit.MINUTES);


        return R.ok();
    }


    /**
     * 用户注册
     * @param vo
     * @param result
     * @param model
     * @return
     */
    @PostMapping("/sms/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result, Model model) {

        //用户注册时会先判断填写的数据是否符合要求
        Map<String, String> map = new HashMap<>();
        if (result.hasErrors()) {
            // 表示提交的数据不合法
           List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                String field = fieldError.getField();
                String defaultMessage = fieldError.getDefaultMessage();
                map.put(field, defaultMessage);
            }
            model.addAttribute("error", map);

            return "/reg";//返回注册页面
        }else {

            // 表单提交的注册的数据是合法的,这时我们就要验证，验证码是否正确
            String code =(String) redisTemplate.opsForValue().get(SmsConstant.SMS_CODE_PERFIX+vo.getPhone());
            code=code.split("_")[0];
            System.out.println("oooooooooooo"+code);
            if (!code.equals(vo.getCode())) {
                //说明验证码不正确
                map.put("code", "验证码不正确");
                model.addAttribute("error", map);
                return "/reg";//返回注册页面
            } else {
                //说明验证码正确
                redisTemplate.delete(SmsConstant.SMS_CODE_PERFIX+vo.getPhone());
                //远程调用服务，完成注册功能

                R r = membeFeginService.register(vo);
                if (r.getcode() == 0) {
                    //说明注册成功

                    return "redirect:http://auth.msb.com:30000/login.html";//重定向到登入页面
                }else {
                    //注册失败
                    map.put("msg", r.getcode() + ":" + r.get("msg"));
                    model.addAttribute("error", map);

                    return "/reg";
                }
            }
        }
    }


    /**
     * 登入功能
     * @return
     */
    @PostMapping("/login")
    public String login(LoginVo loginVo,  HttpSession httpSession) {

         R r = membeFeginService.login(loginVo);

        if (r.getcode() == 0) {
            String entity = (String) r.get("entity");
            MemberVO memberVO = JSON.parseObject(entity, MemberVO.class);
            httpSession.setAttribute(AuthConstant.AUTH_SESSION_REDIS,memberVO);
            //表示登入验证成功，跳转到商城首页
            return "redirect:http://auth.msb.com:8040/home";
        }

        httpSession.setAttribute("errors",r.get("msg"));
        //表示登入验证有误，重新返回登入页面
        return "redirect:http://auth.msb.com:30000/login.html";
    }


}
